package com.globaldom.utils;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.globaldom.model.MilResource;
import com.globaldom.model.Person;

public class ResearchUtil {

	private static final Logger log = Logger.getLogger(ResearchUtil.class.getName());

	public String updateResearch(String personID, int researchType) {
		String retCode = "-ERR";

		try {

			if (researchType > 0 && researchType < 100) {
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Person p = pm.getObjectById(Person.class, personID);
				p.setMaxCivilians(p.getMaxCivilians() + 5 + researchType);
				retCode = "CTOT/" + 5;
				pm.close();
			} else if (researchType >= 100 && researchType < 200) {
				int unitType = researchType - 100;
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Query query = pm.newQuery(MilResource.class, "person==pid AND unitType==unit");
				query.declareParameters("String pid, int unit");
				MilResource curResource = ((List<MilResource>) query.execute(personID, unitType)).get(0);
				curResource.setDefendPoint(curResource.getDefendPoint() + 1);
				retCode = "MDEF/" + unitType + "/" + curResource.getDefendPoint();
				pm.close();

			} else if (researchType >= 200 && researchType < 300) {

				int unitType = researchType - 100;
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Query query = pm.newQuery(MilResource.class, "person==pid AND unitType==unit");
				query.declareParameters("String pid, int unit");
				MilResource curResource = ((List<MilResource>) query.execute(personID, unitType)).get(0);
				curResource.setAttackPoint(curResource.getAttackPoint() + 1);
				retCode = "MATT/" + unitType + "/" + curResource.getAttackPoint();
				pm.close();

			}

		} catch (Exception ex) {
log.severe("Error during researching:" + personID + " " +ex.getMessage());
			ex.printStackTrace();
			
		}
		return retCode;

	}

}
